package com.bidevalution.business.impl;

import com.bidevalution.business.dto.SectionInfoDto;
import com.bidevalution.business.service.BeDataSyncService;


import com.bidevalution.dao.entity.*;
import com.bidevalution.dao.mapper.*;
import com.bidevalution.support.util.FileUtil;
import com.bidevalution.support.util.MdbUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.healthmarketscience.jackcess.*;
import com.qtp.core.util.Md5Util;
import com.qtp.core.util.OConvertUtils;
import lombok.extern.log4j.Log4j2;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据同步接口实现类
 * Created by glodon on 2019-08-05.
 */
@Log4j2
@Service
@Transactional(rollbackFor = Exception.class)
public class BeDataSyncServiceImpl implements BeDataSyncService {
    @Autowired(required = false)
    private BeSectionInfoMapper beSectionInfoMapper;

    @Autowired(required = false)
    private BeSectionEnterpriseMapper beSectionEnterpriseMapper;

    @Autowired
    private DynamicDataImportMapper dynamicDataImportMapper;

    @Value("${upload.file.path}")
    private String uploadFilePath;

    @Value("${t9.fileServer.url}")
    private String t9FileServerUrl;
    private Logger log = Logger.getLogger(getClass());
    /**
     * 标段基本信息及其附属数据同步value
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncSectionInfo(SectionInfoDto sectionInfoDto) throws Exception {
        if(sectionInfoDto == null) {
            return;
        }
        //保存标段基本信息
        BeSectionInfo beSectionInfo = sectionInfoDto.getBeSectionInfo();
        if (beSectionInfo == null) {
            return;
        }
        //下载解析招标文件，并存入对应数据库表中
        downAndParseImportFile(beSectionInfo, null, sectionInfoDto.getFileId());
        //add by daizhifeng
        if(StringUtils.isEmpty(beSectionInfo.getTdProjectid())) {
        	return;
        }
        //标段基本信息存入数据库
        beSectionInfoMapper.deleteByPrimaryKey(beSectionInfo.getSeqId());
        beSectionInfoMapper.insert(beSectionInfo);
    }

    /**
     * 同步投标单位报名信息
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncEnterpriseInfo(List<BeSectionEnterprise> beSectionEnterpriseList) throws Exception {
        if(beSectionEnterpriseList == null || beSectionEnterpriseList.size() == 0) {
            return;
        }
        beSectionEnterpriseMapper.bathInsertAndUpdate(beSectionEnterpriseList);
    }

    /**
     * 投标文件附属信息导入
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncBidFileInfo(BeSectionEnterprise beSectionEnterprise) throws Exception {
        if(beSectionEnterprise == null) {
            return;
        }
        //下载解析投标文件，并存入对应数据库表中
        downAndParseImportFile(null, beSectionEnterprise,beSectionEnterprise.getBidfileId());
    }

    /**
     * 下载并解析mdb文件
     *
     * @param beSectionInfo 数据转换对象
     * @param fileId         文件下载id
     * @throws Exception
     */
    private void downAndParseImportFile(BeSectionInfo beSectionInfo, BeSectionEnterprise beSectionEnterprise, String fileId) throws Exception {
        if(fileId == null){
            return;
        }
        String filePath = fileId + "temp.mdb";
        try {
            long startTime = System.currentTimeMillis();
            //下载文件
            FileUtil.downloadFile(t9FileServerUrl + "/down?bucket=2&md5=", fileId, filePath);
            long time = System.currentTimeMillis() - startTime;
            BigDecimal b1 = BigDecimal.valueOf(time);
            BigDecimal b2 = BigDecimal.valueOf(1000);
            double userTime = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println("*****下载投标文件用时（s）*****" + userTime);
            //读取mdb文件
            List<Table> tables = MdbUtils.getTableListFromMdb(filePath);

            //验证表是否存在，不存在则创建
            checkAndCreateTable(tables);

            if(beSectionInfo != null) {
                //批量插入招标文件数据
                parseAndImportTenderTables(tables, beSectionInfo);
            }

            if(beSectionEnterprise != null) {
                //批量插入投标文件数据
                parseAndImportBidTables(tables, beSectionEnterprise);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            MdbUtils.close();
            File file = new File(filePath);
            //如果文件存在则删除
            if (file.exists()) {
                if(!file.delete()){
                    log.error("文件删除异常！");
                }
            }
        }
    }

    /**
     * 招标文件数据解析
     * @param tables
     */
    private void parseAndImportTenderTables(List<Table> tables, BeSectionInfo beSectionInfo) throws Exception {
        List<? extends Column> columnList = null;
        List<List<Object>> insertItems = new ArrayList<>();
        List<String> fields = new ArrayList<>();
        List<Object> list = null;
        //读取表
        for (Table table : tables) {
            if (table.getRowCount() > 0) {
                columnList = table.getColumns();
                insertItems.clear();
                fields.clear();
                int i = 0;
                //读取每列数据
                for (Row row : table) {
                    list = new ArrayList<>();
                    //读取列名
                    for (Column column : columnList) {
                        if (i == 0) {
                            fields.add(column.getName());
                        }
                        list.add(row.get(column.getName()));
                    }
                    i = 1;
                    insertItems.add(list);
                    if(table.getName().equals("td_Project")){
                        beSectionInfo.setTdProjectid(OConvertUtils.getString(row.get("proj_ProjectID")));
                    }
                }
                //插入数据
                insertDatas(insertItems, fields, table.getName());
            }
        }
    }

    /**
     * 投标文件数据解析
     * @param tables
     */
    private void parseAndImportBidTables(List<Table> tables, BeSectionEnterprise beSectionEnterprise) throws Exception {
        List<? extends Column> columnList = null;
        List<List<Object>> insertItems = new ArrayList<>();
        List<String> fields = new ArrayList<>();
        List<Object> list = null;
        FileOutputStream fos = null;
        long time = 0L;
        try {
            //读取表
            for (Table table : tables) {
                if (table.getRowCount() > 0 && table.getName().contains("Bid")) {
                    columnList = table.getColumns();
                    insertItems.clear();
                    fields.clear();
                    fields.add("enterprise_id");
                    int i = 0;
                    //读取每列数据
                    for (Row row : table) {
                        list = new ArrayList<>();
                        list.add(beSectionEnterprise.getSeqId());
                        //读取列名
                        for (Column column : columnList) {
                            if (i == 0) {
                                fields.add(column.getName());
                            }
                            //文件流格式数据上传至文件服务器
                            if (row.get(column.getName()) instanceof byte[]) {
                                long startTime = System.currentTimeMillis();
                                InputStream in = new ByteArrayInputStream((byte[]) row.get(column.getName()));

                                Map<String, Object> param = new HashMap<>();
                                String md5 = Md5Util.getMD5(in);
                                param.put("businessId", md5);
                                byte[] data = (byte[]) row.get(column.getName());
                                String newFilepath = md5 + ".pdf";
                                File file = new File(newFilepath);
                                if (file.exists()) {
                                    if(!file.delete()){
                                        throw new Exception("文件删除异常！");
                                    }
                                }
                                fos = new FileOutputStream(file);
                                fos.write(data, 0, data.length);
                                fos.flush();
                                fos.close();
                                FileUtil.uploadFile(md5, newFilepath, uploadFilePath);
                                long overTime = System.currentTimeMillis() - startTime;
                                time += overTime;
                            }
                            list.add(row.get(column.getName()));
                        }
                        i = 1;
                        insertItems.add(list);
                    }
                    //插入数据
                    insertDatas(insertItems, fields, table.getName());
                }
            }
            BigDecimal b1 = BigDecimal.valueOf(time);
            BigDecimal b2 = BigDecimal.valueOf(1000);
            double userTime = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println("*****附件文件流上传服务器用时（s）*****" + userTime);
        } finally {
            if(fos != null) {
                fos.close();
            }
        }
    }

    /**
     * 数据批量导入
     * @param insertItems   插入数据列表
     * @param fields 列名列表
     * @param tableName 表名
     */
    public void insertDatas(List<List<Object>> insertItems,List<String> fields, String tableName) throws Exception {
        if (!insertItems.isEmpty()) {
            Map<String,Object> params = Maps.newHashMap();
            //这里把数据分成每1000条执行一次，可根据实际情况进行调整
            int count = insertItems.size() / 1000;
            int yu = insertItems.size() % 1000;
            for (int i = 0; i <= count; i++) {
                List<List<Object>> subList = Lists.newArrayList();
                if (i == count) {
                    if(yu != 0){
                        subList = insertItems.subList(i * 1000, 1000 * i + yu);
                    }else {
                        continue;
                    }
                } else {
                    subList = insertItems.subList(i * 1000, 1000 * (i + 1));
                }
                params.put("table_name", tableName);
                params.put("fields", fields);
                params.put("list", subList);
                dynamicDataImportMapper.insertDatas(params);
            }
        }
    }

    /**
     * 验证并创建表结构
     * @param tables
     */
    private void checkAndCreateTable(List<Table> tables) throws Exception {
        StringBuilder sql = new StringBuilder();
        List<? extends Column> columnList = null;
        //读取表
        for (Table table : tables) {
            columnList = table.getColumns();
            if(dynamicDataImportMapper.whetherTheTableExists(table.getName()) == 0){
                sql.delete( 0, sql.length() );
                sql.append("CREATE TABLE ").append(table.getName()).append("(");
                //读取列名
                for (int i=0; i < columnList.size();i++) {
                    if(i == 0) {
                        sql.append(columnList.get(i).getName()).append(" ").append(getParameterType(columnList.get(i)));
                    } else {
                        sql.append(",").append(columnList.get(i).getName()).append(" ").append(getParameterType(columnList.get(i)));
                    }
                }
                if(table.getName().contains("Bid")){
                    sql.append(",enterprise_id VARCHAR(36)");
                }
                try {
                    List<? extends Index.Column> keyColumns = table.getPrimaryKeyIndex().getColumns();
                    sql.append(",primary key (enterprise_id");
                    //读取列名
                    for (int i = 0; i < keyColumns.size(); i++) {
                        sql.append(",").append(keyColumns.get(i).getName());
                    }
                    sql.append(")");
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                sql.append(")");
                dynamicDataImportMapper.createTable(sql.toString());
            }
        }
    }

    /**
     * 列格式转换
     * @param column
     * @return
     */
    private static String getParameterType(Column column) {
        if (("TEXT").equals(column.getType().name())) {
            return "VARCHAR("+column.getLengthInUnits()+")";
        } else if (("OLE").equals(column.getType().name())){
            return "LONGBLOB";
        } else if("SHORT_DATE_TIME".equals(column.getType().name())){
            return "DATETIME";
        } else if("MEMO".equals(column.getType().name())) {
            return "LONGTEXT";
        } else if("LONG".equals(column.getType().name())) {
            return "INT(11)";
        } else if("MONEY".equals(column.getType().name())) {
            return "DECIMAL(20,4)";
        } else if("MEDIUMTEXT".equals(column.getType().name())){
            return "INT(11)";
        }
        return column.getType().name();
    }

}
